<template>
  <div class="backup-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据备份</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleBackup">
              立即备份
            </el-button>
            <el-button type="success" @click="showRestoreDialog">
              恢复数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 备份设置 -->
      <el-form
        ref="settingsForm"
        :model="settings"
        label-width="120px"
        class="backup-settings"
      >
        <el-form-item label="自动备份">
          <el-switch v-model="settings.autoBackup" />
        </el-form-item>

        <template v-if="settings.autoBackup">
          <el-form-item label="备份频率">
            <el-select v-model="settings.frequency">
              <el-option label="每天" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>

          <el-form-item label="备份时间">
            <el-time-picker
              v-model="settings.backupTime"
              format="HH:mm"
              placeholder="选择时间"
            />
          </el-form-item>
        </template>

        <el-form-item label="保留备份数">
          <el-input-number
            v-model="settings.keepCount"
            :min="1"
            :max="30"
          />
          <span class="unit">个</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveSettings">
            保存设置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 备份记录 -->
      <div class="backup-records">
        <h3>备份记录</h3>
        <el-table :data="backupList" style="width: 100%">
          <el-table-column prop="time" label="备份时间" width="180" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.type === 'auto' ? 'info' : 'success'">
                {{ scope.row.type === 'auto' ? '自动' : '手动' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="大小" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                {{ scope.row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  @click="handleDownload(scope.row)"
                >
                  下载
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  @click="handleRestore(scope.row)"
                >
                  恢复
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 恢复数据对话框 -->
    <el-dialog
      v-model="restoreDialogVisible"
      title="恢复数据"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/backup/restore"
        :on-success="handleRestoreSuccess"
        :on-error="handleRestoreError"
        :before-upload="beforeRestore"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将备份文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传系统备份文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import {
  getBackupList,
  createBackup,
  restoreBackup,
  deleteBackup,
  downloadBackup,
  getBackupSettings,
  updateBackupSettings
} from '@/api/backup'

// 备份设置
const settings = reactive({
  autoBackup: true,
  frequency: 'daily',
  backupTime: new Date(2024, 0, 1, 2, 0),
  keepCount: 7
})

// 备份记录
const backupList = ref([])
const loading = ref(false)

// 初始化数据
onMounted(async () => {
  try {
    loading.value = true
    // 获取备份设置
    const settingsData = await getBackupSettings()
    Object.assign(settings, settingsData)
    
    // 获取备份列表
    const { list } = await getBackupList()
    backupList.value = list
  } catch (error) {
    console.error('初始化数据失败:', error)
  } finally {
    loading.value = false
  }
})

// 保存设置
const saveSettings = async () => {
  try {
    await updateBackupSettings(settings)
    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
  }
}

// 立即备份
const handleBackup = async () => {
  try {
    await createBackup()
    ElMessage.success('备份已开始，请稍候...')
    // 刷新备份列表
    const { list } = await getBackupList()
    backupList.value = list
  } catch (error) {
    console.error('创建备份失败:', error)
  }
}

// 恢复备份
const handleRestore = async (backup) => {
  try {
    await ElMessageBox.confirm(
      '确定要恢复到此备份吗？当前数据将被覆盖。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await restoreBackup(backup.id)
    ElMessage.success('数据恢复成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复备份失败:', error)
    }
  }
}

// 下载备份
const handleDownload = async (backup) => {
  try {
    const response = await downloadBackup(backup.id)
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `backup_${backup.id}.zip`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('开始下载备份文件')
  } catch (error) {
    console.error('下载备份失败:', error)
  }
}

// 删除备份
const handleDelete = async (backup) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此备份吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteBackup(backup.id)
    ElMessage.success('备份已删除')
    // 从列表中移除
    const index = backupList.value.findIndex(item => item.id === backup.id)
    if (index > -1) {
      backupList.value.splice(index, 1)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除备份失败:', error)
    }
  }
}

// 恢复上传文件
const handleRestoreSuccess = async () => {
  restoreDialogVisible.value = false
  ElMessage.success('数据恢复成功')
  // 刷新备份列表
  const { list } = await getBackupList()
  backupList.value = list
}

const handleRestoreError = () => {
  ElMessage.error('数据恢复失败')
}
</script>

<style scoped>
.backup-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.backup-settings {
  max-width: 500px;
  margin-bottom: 30px;
}

.unit {
  margin-left: 10px;
  color: #909399;
}

.backup-records h3 {
  margin-bottom: 20px;
}
</style> 